<template>
  <transition>
    <div class="app-upload-img">
      <section>
        <ul class="module-photo me-row">
          <!--{{mediaAttr}}-->
          <li class="item me-col-3" v-for="(item,index) in files">
            <span class="iconfont icon-shanchu" @click="handleDelImg(index,item)"></span>
            <img class="img" :src="item.src"/>
          </li>
          <li class="item me-col-3 item-add">
            <span class="input-upload" @click="handleSelectImg"></span>
            <span class="iconfont add-img icon-xiangjizhuanhuan">添加图片</span>
          </li>
        </ul>

        <div class="button-content">
          <div class="img-note">*建议提供车架号、整车图、破损部位等图片。</div>
          <div class="button-block-6">
            <mt-button type="default" @click="handleClose">取消上传</mt-button>
          </div>
          <div class="button-block-6">
            <mt-button type="danger" @click="handleTest">确认上传</mt-button>
          </div>
        </div>

      </section>

    </div>
  </transition>
</template>

<script>
  import {Button,Toast,Indicator,Radio} from 'mint-ui';

  //  Vue.component(Header.name, Header);
  export default {
    data () {
      return {
        files:[],
        picList:[],
        picIndex:0,
        popupSwiper:false,
        mediaAttr:[],
        post:{
          uploads:[],
        },
        url:'',
        wxConfig:'',
        accessToken:'',
      }
    },
    mounted(){
      this.getOss();

      //  调取微信配置接口
      this.url=location.href;
      var params = new URLSearchParams();
      params.append('url',this.url);
      this.$axios({
        method: 'post',
        url:'gp/cardCancel/getCardCancel',
        data:params
      }).then((res)=> {
        this.wxConfig=res.data;
      this.accessToken=res.data.accessToken;
      this.$wx.config({
        beta: true,// 必须这么写，否则wx.invoke调用形式的jsapi会有问题
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: 'ww523544f7e1e50c46', // 必填，企业微信的corpID
        timestamp:this.wxConfig.timestamp, // 必填，生成签名的时间戳
        nonceStr: this.wxConfig.nonceStr, // 必填，生成签名的随机串
        signature: this.wxConfig.signature,// 必填，签名，见附录1
        jsApiList: ['chooseImage','uploadImage','getLocalImgData','downloadImage'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
      });
    });

    },
    methods:{
      //  删除图片
      handleDelImg(index,item){
        this.files.splice(index, 1);
        this.post.uploads.splice(index, 1);
        this.mediaAttr.splice(index, 1);
        if(item.id!==undefined){
          var params = new URLSearchParams();
          params.append('uploadId',item.id);
          this.$axios({
            method: 'post',
            url:'gp/declaration/uploadDel',
            data:params
          }).then((res)=>{
            if(res.data.statusCode==200){
            Toast({
              message: res.data.message,
              position: 'middle',
              duration:600
            });
          }
        });
        }
      },
      handleSelectImg(){
        this.$wx.ready(()=>{
          var u = navigator.userAgent;
        var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端

        var _this=this;
        var syncUpload = function(localIds){
          var localId = localIds.pop();
          _this.$wx.uploadImage({
            localId: localId.toString(), // 需要上传的图片的本地ID，由chooseImage接口获得
            isShowProgressTips: 1, // 默认为1，显示进度提示
            success: function (res) {
              //res.serverId 返回图片的服务器端ID
              var serverId = res.serverId; // 返回图片的服务器端ID
              const item={
                serverId:res.serverId,
                tag : '',
              }
              _this.mediaAttr.push(item);
              if(localIds.length > 0){
                window.setTimeout(function(){
                  syncUpload(localIds);
                },100);
              }else{
                window.setTimeout(function(){
                  downloadImage(0);
                },100);

              }
            }
          })
        }
        _this.$wx.chooseImage({
          count: 9, // 默认9
          sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
          defaultCameraMode: "batch", //表示进入拍照界面的默认模式，目前有normal与batch两种选择，normal表示普通单拍模式，batch表示连拍模式，不传该参数则为normal模式。（注：用户进入拍照界面仍然可自由切换两种模式）
          success: function (res) {

            var localIds = res.localIds; // 返回选定照片的本地ID列表，

            for(var i=0;i<localIds.length;i++){
              if(isiOS==true){

                _this.$wx.getLocalImgData({
                  localId: localIds[i], // 图片的localID
                  success: function (res) {
                    var localData = res.localData; // localData是图片的base64数据，可以用img标签显示
                    const item={
                      src:localData,
                      tag : '',
                    };
                    _this.files.push(item);
                    console.log(_this.files);

                  },
                  fail: function(res) {
                    console.log(res)
                  }
                });
              }else{
                const item={
                  src:localIds[i],
                  tag : '',
                };
                _this.files.push(item);
              }


            }

            syncUpload(res.localIds)
            // andriod中localId可以作为img标签的src属性显示图片；
            // 而在IOS中需通过上面的接口getLocalImgData获取图片base64数据，从而用于img标签的显示
          }
        });
      })
      },
      /**获取oss配置**/
      getOss(){
        let OSS = require('ali-oss');
        this.client = new OSS({
          region: "oss-cn-shenzhen",
          secure: true,//https
          endpoint: 'oss-cn-shenzhen.aliyuncs.com',
          accessKeyId: "LTAIPCNdQvX5yOwc",
          accessKeySecret: "7bReGAz8bc9aJdK4IAz5KW5fnNOzrQ ",
          bucket: 'rmcbapp'
        });
      },
      toBuffer(ab) {
        var buf = new Buffer(ab.byteLength);
        var view = new Uint8Array(ab);
        for (var i = 0; i < buf.length; ++i) {
          buf[i] = view[i];
        }
        return buf;
      },
      handleTest(){

        this.getOss();
        var that=this;
        that.post.uploads=[];
        for(var i=0;i<that.mediaAttr.length;i++){

          const mediaId = that.mediaAttr[i].serverId; // 微信多媒体文件id
          const tag = that.mediaAttr[i].tag;
            Indicator.open({
              text: '图片上传中...',
              spinnerType: 'snake'
            });
            that.$axios({
              method: 'get',
              url:'wx/cgi-bin/media/get?access_token='+that.accessToken+'&media_id='+mediaId,
              responseType:'arraybuffer',
            }).then((res)=>{
              // arrayBuffer转Buffer

            var buffer = that.toBuffer(res.data);
            var destPath = 'demand/'+mediaId+'.jpg'; // OSS文件路径
            console.log(buffer)
            var postitem={}
            that.client.put(destPath, buffer).then((result) => {
              console.log('图片上传阿里云结果', result);

             Indicator.close();
             that.$emit('popupClose');
              postitem={
                bucketName:'rmcbapp',
                fileLocate:'',
                fileType:0,
                sourceFileName:mediaId+'.jpg',
                ossPath:result.name,
                ossKey:'rmcbapp/'+result.name,
                etag:result.res.headers.etag
              }
              that.post.uploads.push(postitem);
              console.log(that.post.uploads)
              that.$emit('filesData',that.files)
              that.$emit('uploadsData',that.post.uploads)
//              if(that.post.uploads.length==i){
//                Indicator.close();
//                Toast({
//                  message: '上传成功',
//                  position: 'middle',
//                  duration:500
//                });
//                this.$emit('popupClose');
//              }
          }).catch((err) => {
              console.log(err)
            Toast({
              message: '上传失败',
              position: 'middle',
              duration:500
            });
          });
          })
        };
      },
      handleClose(){
        this.$emit('popupClose');
      },
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->

<style>

  .app-upload-img{
    background: #fff;
  }
  .app-upload-img .module-photo .item-add{
    border:1px dashed #ddd;
  }
  .app-upload-img .add-img{
    display: block;
    padding:22px 0 0;
    height: 100px;
    text-align: center;
    color: #888;
  }
  .app-upload-img .add-img:before{
    display: block;
    margin:0 auto 4px;
    font-size:24px;
  }
  .mint-indicator-wrapper{
    z-index:1000001;
  }
  .app-upload-img .module-photo{
    padding:16px 0 0;
  }
  .app-upload-img .module-photo .addon{
    padding:0 12px ;
    font-size: 16px;
    color: #666;
  }
  .app-upload-img .module-photo{
    padding:14px 12px 0;
    margin: 0;
  }
  .app-upload-img .module-photo .item{
    position: relative;
    height: 100px;
    padding:0 12px 0 0;
    margin:0 0 20px;
  }
  .app-upload-img .module-photo img{
    width: 100%;
    height: 100px;
  }
  .app-upload-img .module-photo .icon-shanchu{
    background:rgba(225,225,225,0.5) !important;
    position: absolute;
    top:0;
    right:12px;
    width: 24px;
    height: 24px;
    font-size:18px !important;
    color:#fff;
    text-align: center;
    line-height: 28px;
  }
  .app-upload-img .module-photo .item-add .icon-jiahao{
    display: block;
    height: 100px;
    font-size: 50px;
    color: #ddd;
    line-height: 100px;
    text-align: center;
    border:1px dashed #ddd;
  }
  .app-upload-img .input-upload {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 4;
    opacity: 0;
    font-size: 0;
    width: 100%;
  }
  .app-upload-img .img-note{
    text-align: left;
    padding: 0  0 14px;
    color: #c34853;
  }
  .app-upload-img .button-content{
    padding:12px 24px ;
    text-align: center;
  }
  .app-upload-img .button-content .mint-button{
    font-size: 16px;
  }
  .app-upload-img .button-block-6{
    display: inline-block;
    width:46%;
    padding:0 8px;
  }
  .app-upload-img .button-content .mint-button--default{
    background-color:#fff;
  }
  .app-upload-img .button-content .mint-button{
    width: 100%;
    font-size: 16px;
  }
  .me-col-3{
    width:33.2% !important;
  }
</style>
